package com.majorty.mail.controller;

import com.majorty.mail.util.JsonTool;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;

import java.io.BufferedReader;

import javax.servlet.http.HttpServletRequest;

/**
 * Controller基类
 * @date 2018年6月2日 下午9:49:18
 * @since JDK 1.8
 * @author yang
 * @version 1.0
 */
@Controller
public class BaseController {
	private static Logger logger = LoggerFactory.getLogger(BaseController.class);
	

	/**
	 * 解析请求头消息
	 * @param req
	 * @return
	 * @date 2018年1月31日 下午5:17:23
	 * @author yangqiang
	 */
	public JSONObject ParseMsg(HttpServletRequest req) {
		JSONObject msgBody = null;
		try {
			String body = readReqMsg(req);
			if (body.length() < 1024) {
				req.getSession().setAttribute("requestbody", body);
			} else {
				req.getSession().setAttribute("requestbody", "body too large");
			}
			msgBody = new JSONObject(body);
			logger.info("request body: {}.", msgBody);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return msgBody;
	}

	/**
	 * 解析请求头消息  
	 * --因做了xss脚本攻击做了防御所以在这便不再转译
	 * 
	 * @param req
	 * @param valueClass
	 * @return
	 */
	public <V> V ParseMsg(HttpServletRequest req, Class<V> valueClass) {
		String msgBody = readReqMsg(req);
		logger.info("request uri: {}.", req.getRequestURI());
		logger.info("request body: {}.", msgBody);
		if (!StringUtils.isEmpty(msgBody)) {
			if (msgBody.length() < 1024) {
				req.getSession().setAttribute("requestbody", msgBody);
			} else {
				req.getSession().setAttribute("requestbody", "body too large");
			}
			return JsonTool.jsonToObject(msgBody, valueClass, false);
		}
		return null;
	}
	 
	/**
	 * 读取请求信息
	 * 
	 * @param request
	 * @return
	 * @date 2018年1月31日 下午5:20:45
	 * @author yangqiang
	 */
	public String readReqMsg(HttpServletRequest request) {
		StringBuffer reqMsg = new StringBuffer();
		BufferedReader reader;
		try {
			reader = request.getReader();
			String str = "";
			while ((str = reader.readLine()) != null) {
				reqMsg.append(str);
			}
			return reqMsg.toString();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new RuntimeException(e);
		}
    }


    
}
